import React, { useEffect, useState } from 'react'
import style from './periodItem.module.scss'
import { IPeriod } from '../../../starter/model/interfaces'
import dayjs from 'dayjs'
import { DATE_FORMAT } from '../../../starter/constants'
import { Input } from 'antd'
import { DeleteOutlined, UndoOutlined } from '@ant-design/icons'
import { useAppSelector } from '../../../starter/hooks/redux'
import { useActions } from '../../../starter/hooks/actions'

interface IPeriodItem {
  period: IPeriod,
  isSelected: boolean
  showCheckbox: boolean
}
const PeriodItem = ({period, isSelected, showCheckbox}: IPeriodItem) => {
  const [isDoRemove, setIsDoRemove] = useState(false)
  const { doRemovePeriods } = useAppSelector(state => state.tmp)
  const { setDoRemoveTmpPeriods} = useActions()
  useEffect(() => {
    if (doRemovePeriods.find(item => item.id === period.id)) {
      setIsDoRemove(true)
    } else {
      setIsDoRemove(false)
      }
  }, [doRemovePeriods])

  const deleteHandler = (event:  React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
    event.stopPropagation()
    const _period = doRemovePeriods.find(item => item.id === period.id)

    if (_period) {
      setDoRemoveTmpPeriods(doRemovePeriods.filter(item => item.id !== period.id))
    } else {
      setDoRemoveTmpPeriods([...doRemovePeriods, period])
    }
  }

  return (
    <div className={style.wrapper}>
      <div className={style.data} >
        {
          showCheckbox &&
          <Input className={style.inputWrapper} type={'checkbox'} checked={isSelected}/>
        }
        <div className={ isDoRemove ? style.isDoRemove : ''}>
          {`С ${dayjs(period.startTime).format(DATE_FORMAT)} ПО ${dayjs(period.endTime).format(DATE_FORMAT)}`}
        </div>
      </div>
      <div className={style.buttonSet}>
        {
          isDoRemove && !showCheckbox &&
          <UndoOutlined
            className={style.removeIcon}
            onClick={deleteHandler}
          />
        }
        {
          !isDoRemove && !showCheckbox &&
          <DeleteOutlined
            className={style.removeIcon}
            onClick={deleteHandler}
          />
        }

      </div>

    </div>
  )
}

export default PeriodItem
